package com.yxq.mdt.app.modules.webview.ui;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.UMShareAPI;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.App;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.base.RespBase;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.event.EventWxPay;
import com.yxq.mdt.app.model.ShareBean;
import com.yxq.mdt.app.modules.auction.ui.BecomeTeamAc;
import com.yxq.mdt.app.modules.bottomsheet.ShareSheetDialog;
import com.yxq.mdt.app.modules.personal.bean.AddressListBean;
import com.yxq.mdt.app.modules.personal.ui.activity.MainPersonalShippingAddressAc;
import com.yxq.mdt.app.modules.pm.bean.ShareActivityBean;
import com.yxq.mdt.app.modules.webview.bean.WxPayFromBean;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.WXUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.DWebView;

@Route(path = RouteTable.ROUTER_ACTIVITY_WEB)
public class MiWebViewActivity extends BaseActivity {

    @Autowired
    String url = "";
    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.web)
    DWebView web;
    String title = "";
    CompletionHandler<String> handlerAddress;
    CompletionHandler<String> handlerTeamLeader;
    CompletionHandler<String> handlerWxPayr;
    IWXAPI api;
    ShareSheetDialog shareSheetDialog;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    //5.0以下使用
    private com.tencent.smtt.sdk.ValueCallback<Uri> uploadMessage;
    // 5.0及以上使用
    private com.tencent.smtt.sdk.ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private String pmUrlIndex = "http://pm.quai69.com/index.html";
    private String pmUrlIndexEnd = "http://pm.quai69.com/indexend.html";

    @Override
    public int getLayoutId() {
        return R.layout.activity_mi_web_view;
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        if ("release".equals(BuildConfig.RELEASE)) {
            pmUrlIndex = "http://pm.quai69.com/index.html";
            pmUrlIndexEnd = "http://pm.quai69.com/indexend.html";
        } else if ("release_pre".equals(BuildConfig.RELEASE)) {
            pmUrlIndex = "http://testpm.quai69.com/index.html";
            pmUrlIndexEnd = "http://testpm.quai69.com/indexend.html";
        } else {
            pmUrlIndex = "http://testpm.quai69.com/index.html";
            pmUrlIndexEnd = "http://testpm.quai69.com/indexend.html";
        }
        initWebView();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constant.WECHAT_ID);
        EventBus.getDefault().register(this);
    }

    public class JsApi {
        //同步API
        @JavascriptInterface
        public String testSyn(Object msg) {
            return msg + "［syn call 东鹏哥牛批！］";
        }

        //异步API
        @JavascriptInterface
        public void testAsyn(Object msg, CompletionHandler<String> handler) {
            handler.complete(msg + " [ asyn call东鹏哥牛批！]");
        }

        /**
         * 获取token
         *
         * @param msg
         * @return token
         */
        @JavascriptInterface
        public String getToken(Object msg) {
            if (BuildConfig.DEBUG) {
                Log.e("浏览器", "TOKEN:" + Constant.getLbsUserToken());
            }
            return Constant.getLbsUserToken();
        }

        /**
         * token失效，App跳转登录页面，重新登录
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean tokenInvalid(Object msg) {
            loginOut();
            return true;
        }

        /**
         * 跳转申请成为团长页面
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean intentBecomeTeamLeader(Object msg) {
            Intent intent = new Intent(mActivity, BecomeTeamAc.class);
            startActivityForResult(intent, 10010);
            return true;
        }

        /**
         * 跳转申请成为团长页面
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean intentBecomeTeamLeader(Object msg, CompletionHandler<String> handler) {
            handlerTeamLeader = handler;
            Intent intent = new Intent(mActivity, BecomeTeamAc.class);
            startActivityForResult(intent, 10010);
            return true;
        }

        /**
         * 跳转新增收货地址页面 (同步方法)
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean intentAddressManager(Object msg) {
            Intent intent = new Intent(mActivity, MainPersonalShippingAddressAc.class);
            intent.putExtra("from", "h5");
            startActivityForResult(intent, 10086);
            return true;
        }

        /**
         * 跳转新增收货地址页面 (异步方法)
         *
         * @param msg
         * @param handler 回调方法
         * @return
         */
        @JavascriptInterface
        public boolean intentAddressManager(Object msg, CompletionHandler<String> handler) {
            handlerAddress = handler;
            Intent intent = new Intent(mActivity, MainPersonalShippingAddressAc.class);
            intent.putExtra("from", "h5");
            startActivityForResult(intent, 10086);
            return true;
        }

        /**
         * 返回上一页
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean returnToPreviousPage(Object msg) {
            finish();
            return true;
        }

        /**
         * 分享
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean share(Object msg) {
            if (shareSheetDialog != null) {
                shareSheetDialog.dismiss();
            }
            if (msg != null && msg.toString().contains("pmGoodsId")) {
                ShareActivityBean jsonObject = JSON.parseObject(msg.toString(), ShareActivityBean.class);
                ShareBean shareBean = new ShareBean();
                shareBean.setTitle(jsonObject.getInfo().getGoodsName() + "￥" + jsonObject.getInfo().getPrice());//标题
                shareBean.setText("社交电商新玩法 价格超实惠  参与出价即可获得分佣");//文本
                shareBean.setShareType("0");//图文分享
                shareBean.setShareTypeAPP(4);
                shareBean.setHandleId(jsonObject.getPmGoodsId());
                if (jsonObject.getInfo().getGoodsImg() != null) {
                    shareBean.setImageUrl(jsonObject.getInfo().getGoodsImg());//LOGO
                } else {
                    shareBean.setImageUrl("https://yxqoss.oss-cn-hangzhou.aliyuncs.com/gs_app/init/727c432c9e186a11.png");//LOGO
                }
                //http://192.168.110.61/webdetail.html?pmGoodsId=708&platform=2&parent_id=13612345678
                if (!"release".equals(BuildConfig.RELEASE)) {
                    shareBean.setUrl("http://testpm.quai69.com/webdetail.html?pmGoodsId=" + jsonObject.getPmGoodsId() + "_2_" + getParentId());//分享URL
                } else {
                    shareBean.setUrl("http://pm.quai69.com/webdetail.html?pmGoodsId=" + jsonObject.getPmGoodsId() + "_2_" + getParentId());
                }
                shareSheetDialog = new ShareSheetDialog(shareBean, false);
                shareSheetDialog.show(getSupportFragmentManager(), "shareSheetDialog");
            } else {
                shareSheetDialog = new ShareSheetDialog();
                shareSheetDialog.show(getSupportFragmentManager(), "shareSheetDialog");
            }
            return true;
        }

        private String getParentId() {

            return !TextUtils.isEmpty(Constant.getLoginUser().getBinding()) ? Constant.getLoginUser().getBinding() : "0";
        }

        /**
         * 分享 带参数
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public boolean shareWithParams(Object msg) {
            if (msg == null) {
                ToastUtils.showShort("分享内容不能为空");
                return false;
            }
            if (shareSheetDialog != null) {
                shareSheetDialog.dismiss();
            }
            shareSheetDialog = new ShareSheetDialog(msg.toString());
            shareSheetDialog.show(getSupportFragmentManager(), "shareSheetDialog");
            return true;
        }

        /**
         * 返回昵称
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public String getNickName(Object msg) {
            return Constant.getSocialUser().getGsName();
        }


        /**
         * 返回用户id
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public String getUserId(Object msg) {
            return Constant.getLbsUserID();
        }

        /**
         * 返回设备类型
         *
         * @param msg
         * @return
         */
        @JavascriptInterface
        public String getDeviceType(Object msg) {
            return "Android";
        }

        @JavascriptInterface
        public boolean WxPay(Object msg, CompletionHandler<String> handler) {
            if (msg == null) {
                Log.e("H5微信支付", "msg is null");
                if (handler != null) {
                    RespBase<String> respBase = new RespBase<>();
                    respBase.setMsg("支付失败,支付参数缺失!");
                    respBase.setCode(-1);
                    handler.complete(JSON.toJSONString(respBase));
                }
                return false;
            }
            handlerWxPayr = handler;
            if (BuildConfig.DEBUG) {
                Log.e("H5微信支付", msg.toString());
            }
            WxPayFromBean resultWxBean = JSON.parseObject(msg.toString(), WxPayFromBean.class);
            invokeWxPay(resultWxBean);
            return true;
        }
    }

    private void initWebView() {
        title = getIntent().getStringExtra("title");
        titlebar.getCenterTextView().setText(title != null ? title : "");
        web.setWebViewClient(new WebViewClient());
        web.addJavascriptObject(new JsApi(), null);
        web.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
        // 支持与JS交互
        url = getIntent().getStringExtra("url");
        if (!TextUtils.isEmpty(url)) {
            web.loadUrl(url);
        } else {
            web.loadUrl(" ");
        }
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                //显示标题
                if (!isFinishing() && titlebar != null) {
                    titlebar.getCenterTextView().setText(s);
                }
            }

            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                super.onProgressChanged(webView, newProgress);
                //显示加载进度条
                try {
                    if (progressBar != null) {
                        if (newProgress == 100) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            if (progressBar.getVisibility() == View.GONE)
                                progressBar.setVisibility(View.VISIBLE);
                            progressBar.setProgress(newProgress);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //For Android  >= 4.1
            @Override
            public void openFileChooser(com.tencent.smtt.sdk.ValueCallback<Uri> valueCallback, String s, String s1) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = valueCallback;
                openImageChooserActivity();
                return true;
            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (web != null) {
            web.destroy();
            web = null;
        }
        super.onDestroy();
    }

    @Override
    protected void back() {
        goBack();
    }

    @Override
    public void onBackPressed() {
        goBack();
    }

    /**
     * 退出界面
     */
    private void goBack() {

        if (web.getUrl().equals(url) || web.getUrl().equals(pmUrlIndex) || web.getUrl().equals(pmUrlIndexEnd)) {
            finish();
        } else {
            if (web.canGoBack()) {
                web.goBack();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            //处理返回的图片，并进行上传
            if (data != null && resultCode == RESULT_OK) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (uploadMessageAboveL != null) {
                        uploadMessageAboveL.onReceiveValue(new Uri[]{});
                        uploadMessageAboveL = null;
                        return;
                    }
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                    return;
                }
            }
            return;
        }
        if (RESULT_OK == resultCode) {
            if (requestCode == 10010) {
                if (handlerTeamLeader != null) {
                    RespBase<String> respBase = new RespBase<>();
                    respBase.setMsg("成功");
                    respBase.setCode(200);
                    handlerTeamLeader.complete(JSON.toJSONString(respBase));
                    handlerTeamLeader = null;
                }
            } else if (requestCode == 10086) {
                if (handlerAddress != null && data != null) {
                    AddressListBean.ListBean addressBean = (AddressListBean.ListBean) data.getSerializableExtra("data");
                    if (addressBean != null) {
                        //返回给Js新增的收货地址Json字符串
                        handlerAddress.complete(JSON.toJSONString(addressBean));
                    } else {
                        handlerAddress.complete(JSON.toJSONString(new AddressListBean.ListBean()));
                    }
                    handlerAddress = null;
                }
            }
        }
        UMShareAPI.get(MiWebViewActivity.this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 登录过期 重新登录
     */
    private void loginOut() {
        new Thread(() -> EMClient.getInstance().logout(true)).start();
        Hawk.delete(SPKey.SP_KEY_USER_MY_INFO);
        Hawk.delete(SPKey.SP_KEY_USER_INFO);
        App.getInstance().exit();
        ARouter.getInstance().build(RouteTable.ROUTER_ACTIVITY_LOGIN).withBoolean("intentMain", true).navigation();
        finish();
    }


    private void invokeWxPay(WxPayFromBean orderPayResultWxBean) {

        PayReq req = new PayReq();

        req.appId = Constant.WECHAT_ID;//微信开放平台审核通过的应用APPID
        req.partnerId = Constant.WECHAT_MCH_ID;//微信支付分配的商户号
        req.prepayId = orderPayResultWxBean.getCanshu().getPackageX().replaceAll("prepay_id=", "");//预支付交易会话ID
        req.nonceStr = orderPayResultWxBean.getCanshu().getNonceStr();//随机字符串，不长于32位。
        req.timeStamp = orderPayResultWxBean.getCanshu().getTimeStamp();   //时间戳
        req.packageValue = "Sign=WXPay"; //扩展字段 暂填写固定值Sign=WXPay
        req.sign = WXUtil.genPayReq(req, orderPayResultWxBean); //二次签名
        api.sendReq(req);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayMessage(EventWxPay message) {
        switch (message.code) {
            case 0://支付成功
                ToastUtils.showShort("支付成功");
                if (handlerWxPayr != null) {
                    RespBase<String> respBase = new RespBase<>();
                    respBase.setMsg("支付成功");
                    respBase.setCode(0);
                    handlerWxPayr.complete(JSON.toJSONString(respBase));
                    handlerWxPayr = null;
                }
                break;
            case -1://支付失败
                ToastUtils.showShort("支付失败");
                if (handlerWxPayr != null) {
                    RespBase<String> respBase = new RespBase<>();
                    respBase.setMsg("支付失败");
                    respBase.setCode(-1);
                    handlerWxPayr.complete(JSON.toJSONString(respBase));
                    handlerWxPayr = null;
                }
                break;
            case -2://取消成功
                ToastUtils.showShort("取消支付");
                if (handlerWxPayr != null) {
                    RespBase<String> respBase = new RespBase<>();
                    respBase.setMsg("取消支付");
                    respBase.setCode(-2);
                    handlerWxPayr.complete(JSON.toJSONString(respBase));
                    handlerWxPayr = null;
                }
                break;
        }
    }

    private void openImageChooserActivity() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)//最大选择数目
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(FILE_CHOOSER_RESULT_CODE);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        List<LocalMedia> images = PictureSelector.obtainMultipleResult(intent);
        LocalMedia media = images.get(0);
        Uri newUri = null;
        newUri = Uri.fromFile(new File(media.getCompressPath()));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (uploadMessageAboveL != null) {
                if (newUri != null) {
                    uploadMessageAboveL.onReceiveValue(new Uri[]{newUri});
                    uploadMessageAboveL = null;
                    return;
                }
            }
        } else if (uploadMessage != null) {
            if (newUri != null) {
                uploadMessage.onReceiveValue(newUri);
                uploadMessage = null;
                return;
            }
        }
    }
}
